#!/bin/sh

# check args see if user gives us the necessary stuff
if [ $# -lt 1 ]; then
    echo "\
usage: automk <lang> [-s] [-n name] [-l lib] [-o outputformat]
  - available langs are c, cpp, py, java, md, epub, ms
  - options for all langs:
    - app name '-n': automk <lang>
  - options for c users:
    - linking options '-l': automk <lang> [-l<lib> ...]
    - ｓｕｃｋｌｅｓｓ flags with '-s': automk <lang> [-s]
  - options for java users:
    - automatically run application with '-r': automk <lang> [-r]

for effective use you would do something like: automk -nfunkyname c -lm > Makefile"
    exit 1
fi

# default options
app=main
preamble='OPTIONS:=\n'
# these two have to be set by each lang
lang=
comp=
output=
# fancy but unneccessary most of the time
variant=
run=
# auxiliary
last=0

# loop args for name first
for arg in "$@"; do
    if [ ${app} = "custom" ]; then
        app=${arg}
        continue
    fi

    case ${arg} in
        -n)
            app=custom
    esac
done

# loop args
for arg in "$@"; do

    if [ ${last} = "-l" ]; then
        preamble=${preamble}"OPTIONS+= -l ${arg}\n"
        last=0
        continue
    fi

    # check every arg
    case ${arg} in
        -l)
            last=-l
            ;;
        -s)
            comp="gcc -Wall -std=c99 -pedantic -g ${app}.${lang} -o ${app} \$(OPTIONS)"
            ;;
        c)
            preamble='OPTIONS:=\n'
            lang=c
            comp="gcc -Wall -g ${app}.${lang} -o ${app} \$(OPTIONS)"
            ;;
        # unironically using cpp with regular makefiles (git ｓｕｃｋｌｅｓｓ)
        cpp)
            echo 'not implemented yet'
            exit 1
            ;;
        py)
            preamble="# change this if you need to do so\nOPTIONS:=/bin/python${variant}\n"
            comp="python${variant} ${app}.py \$(OPTIONS)"
            lang=py
            ;;
        -r)
            comp=${comp}"\n\tjava $(echo ${app} | sed -e "s/\b./\u\0/")"
            ;;
        java)
            lang=java
            # find all java source files and compile them
            # after having them sorting by filename length (descending)
            # this is done to avoid errors due to caching madness
            comp="javac \$(shell find . -name \*.java | sort -n)"
            ;;
        md)
            lang=md
            comp="pandoc ${app}.${lang} -V fontsize:12pt -V geometry:\"top=2cm, bottom=2cm\" -o ${app}.pdf"
            ;;
        epub)
            lang=md
            comp="pandoc ${app}.${lang} -o ${app}.epub"
            ;;
        ms)
            lang=ms
            comp="groff -${lang} ${app}.${lang} -T pdf > ${app}.pdf"
    esac
done

echo ${preamble}
echo "${app}: ${app}.${lang}"
echo "\t${comp}"
echo "\nclean:\n\trm -rf ${app}"
